<script setup lang="ts">
import type { ColorProps } from '@/types';

import {
  type ComponentInternalInstance,
  computed,
  getCurrentInstance,
  ref,
  watch,
} from 'vue';

import { useAppStore } from '@/store';

defineOptions({
  name: 'Color',
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const appStore = useAppStore();
const COLOR_PRESET: Array<ColorProps> = proxy?.$config.setting
  .color as Array<ColorProps>;
const defaultColor = computed(() => appStore.setting.color);
const modelValue = ref<string>(defaultColor.value || 'default');
const defaultOpacity = computed(() => appStore.setting.opacity);
const opacityValue = ref<number>(defaultOpacity.value || 20);

function activeClass(color: string): string[] {
  return color === modelValue.value ? ['outline-box-active'] : [];
}

watch(
  () => modelValue.value,
  (val) => {
    appStore.updateSetting({ color: val });
  },
);

watch(
  () => opacityValue.value,
  (val) => {
    appStore.updateSetting({ opacity: val });
  },
);
</script>
<template>
  <div class="content">
    <template v-for="color in COLOR_PRESET" :key="color.name">
      <div
        class="flex flex-col cursor-pointer"
        @click="modelValue = color.name"
      >
        <div
          :class="activeClass(color.name)"
          class="flex-col justify-center gap-2 py-4 outline-box px-9"
        >
          <div
            :style="{ backgroundColor: color.color }"
            class="relative flex items-center justify-center rounded-full size-5 hover:scale-110"
          >
            <svg
              v-if="modelValue === color.name"
              class="h-3.5 w-3.5 text-white"
              height="1em"
              viewBox="0 0 15 15"
              width="1em"
            >
              <path
                clip-rule="evenodd"
                d="M11.467 3.727c.289.189.37.576.181.865l-4.25 6.5a.625.625 0 0 1-.944.12l-2.75-2.5a.625.625 0 0 1 .841-.925l2.208 2.007l3.849-5.886a.625.625 0 0 1 .865-.181"
                fill="currentColor"
                fill-rule="evenodd"
              />
            </svg>
          </div>
        </div>
        <div class="mt-2 text-xs text-center text-muted-foreground">
          {{ color.label }}
        </div>
      </div>
    </template>
    <div class="flex w-[340px] cursor-pointer flex-col">
      <div class="flex-center h-[50px] w-full flex-col gap-2 px-9">
        <label class="slider">
          <label class="ml-4" for="opacity">{{ opacityValue }}%</label>
          <input
            v-model="opacityValue"
            class="level"
            max="100"
            min="0"
            name="opacity"
            type="range"
          />
        </label>
      </div>
      <div class="mt-2 text-xs text-center text-muted-foreground">透明度</div>
    </div>
  </div>
</template>
